<?php

namespace app\api\controller\v2;

use app\common\controller\Api;
use app\common\library\BankMatch;
use app\common\library\CreateUser;
use app\common\library\Pingpp;
use app\common\library\Sms;
use think\Db;
use think\Validate;

/**
 * 众包费接口
 */
class Bank extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function saveBank() {
        $data = $this->request->post();

        if ($data['mobile'] && !Validate::regex($data['mobile'] , "^1\d{10}$"))
        {
            $this->error('手机号填写错误');
        }

        if (!Sms::check($data['mobile'] , $data['code'], 'renzheng'))
        {
            $this->error('验证码错误');
        }


        //获取用户银行卡信息
        $user = $this->auth->getUser();//当前临时用户
        if ( $user->is_renzheng  == 1){
            $this->error('用户已认证');
        }
        BankMatch::instance()->match($data['bank_card']); //卡号认证
        //必须先认证
        if (!$user->identity_card || !$user->identity_card_front) {
            $this->error('请先进行实名认证');
        }

        $identifcation['identity_card'] = $user->identity_card;
        $identifcation['real_name'] = $user['real_name'];
        $identifcation['bank_card'] = $data['bank_card'];
        $identifcation['mobile'] = $data['mobile'];
        //银行卡认证
        (new Pingpp())->identificationBank($identifcation);
        try {
            $identifcation['user_id'] = UID;
            $identifcation['type'] = 0;
            CreateUser::instance()->createBank($identifcation, $user);
            $user->is_renzheng = 1;
            $user->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('银行卡认证成功', CreateUser::instance()->userInfo());
    }

    /**
     * 获取银行卡列表
     */
    public function getBanks() {
        $where['user_id'] = UID;
        $list = Db::name('account_bank')->useSoftDelete('deletetime')->where($where)->select();
        $typeList = [
            0 => '银行卡',
            1 => '支付宝号',
            2 => '微信号'
        ];
        foreach ($list as $k => &$v) {
            /*let reg = /^(\d{4})(\d*)(\d{4})$/;
            var str = "1213324343555454";
            str = str.replace(reg, function(a, b, c, d) {
                    return b + c.replace(/\d/g, "*") + d;
            });*/
            $v['type_name'] = $typeList[$v['type']];

        }
    }
}